package com.gin.no_gay_alliance.adpter;

import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;

import androidx.annotation.NonNull;

import com.gin.common.utils.TimeUtils;
import com.gin.no_gay_alliance.adpter.base.BaseBindingRecyclerViewAdapter;
import com.gin.no_gay_alliance.app.MyApplication;
import com.gin.no_gay_alliance.databinding.ItemReleaseBinding;
import com.gin.no_gay_alliance.utils.AlertDialogUtils;
import com.gin.no_gay_alliance.utils.ViewUtils;
import com.gin.no_gay_alliance.viewmodel.AppRelease;

import java.util.List;

/**
 * @author : ginstone
 * @version : v1.0.0
 * @since : 2023/9/11 00:39
 **/
public class ReleaseAdapter extends BaseBindingRecyclerViewAdapter<ItemReleaseBinding, AppRelease> implements View.OnClickListener {
    public ReleaseAdapter(Context context) {
        super(context);
    }

    public ReleaseAdapter(@NonNull Context context, @NonNull List<AppRelease> data) {
        super(context, data);
    }

    /**
     * 绑定数据
     *
     * @param holder
     * @param b        绑定对象
     * @param position 位置
     * @param item
     */
    @Override
    protected void onBindViewHolder(ViewHolder<ItemReleaseBinding> holder, @NonNull ItemReleaseBinding b, int position, AppRelease item) {
        b.getRoot().setTag(item);
        b.getRoot().setOnClickListener(this);

        ViewUtils.setGone(!item.preRelease, b.tvPreRelease);
        b.tvTagName.setText(item.tagName);
        b.tvTime.setText(TimeUtils.format(item.createdAt));
        b.tvContent.setText(item.content);
    }

    @NonNull
    @Override
    protected ItemReleaseBinding buildBinding(LayoutInflater inflater) {
        return ItemReleaseBinding.inflate(inflater);
    }

    @Override
    public void onClick(View v) {
        AppRelease item = (AppRelease) v.getTag();
        List<String> urls = item.findUrls();
        if (urls.isEmpty()) {
            handler.toast("该版本没有下载地址");
            return;
        }
        String url = urls.get(0);

        String title = String.format("下载版本: %s %s", item.tagName, item.preRelease ? "[预览版]" : "");
        AlertDialogUtils.showConfirm(context, title, "即将下载: " + url, (dialog, which) -> {
            if (which == DialogInterface.BUTTON_POSITIVE) {
                MyApplication.app.managerFactory.getUpgradeManager().downloadRelease(item);
            }
        });
    }

}
